package com.mrd.payClient.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**
 * 基于 httpclient 的 http工具类
 * @author han
 *
 */
public class HttpClientUtils {

    private static final CloseableHttpClient httpClient;
    public static final String CHARSET = "UTF-8";

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    /**
     * HTTP Get 获取内容
     * @param url  请求的url地址
     * @param params	请求的参数
     * @return	页面内容
     */
    public static String doGet(String url,Map<String,String> params) throws Exception{
    	if(StringUtils.isEmpty(url)){
    		return null;
    	}
		if(params != null && !params.isEmpty()){
			List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
			for(Map.Entry<String,String> entry : params.entrySet()){
				String value = entry.getValue();
				if(value != null){
					pairs.add(new BasicNameValuePair(entry.getKey(),value));
				}
			}
			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
		}
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = httpClient.execute(httpGet);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 200) {
			httpGet.abort();
			throw new RuntimeException("HttpClient,error status code :" + statusCode);
		}
		HttpEntity entity = response.getEntity();
		String result = null;
		if (entity != null){
			result = EntityUtils.toString(entity, "utf-8");
		}
		EntityUtils.consume(entity);
		response.close();
		return result;
    }
    
    /**
     * HTTP Post 获取内容
     * @param url  请求的url地址
     * @param params	请求的参数
     * @param charset	编码格式
     * @return	页面内容
     */    
    public static String doPost(String url,Map<String,String> params) throws Exception{
    	if(StringUtils.isEmpty(url)){
    		return null;
    	}
    	
		List<NameValuePair> pairs = null;
		if(params != null && !params.isEmpty()){
			pairs = new ArrayList<NameValuePair>(params.size());
			for(Map.Entry<String,String> entry : params.entrySet()){
				String value = entry.getValue();
				if(value != null){
					pairs.add(new BasicNameValuePair(entry.getKey(),value));
				}
			}
		}
		HttpPost httpPost = new HttpPost(url);
		if(pairs != null && pairs.size() > 0){
			httpPost.setEntity(new UrlEncodedFormEntity(pairs,CHARSET));
		}
		CloseableHttpResponse response = httpClient.execute(httpPost);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 200) {
			httpPost.abort();
			throw new RuntimeException("HttpClient,error status code :" + statusCode);
		}
		HttpEntity entity = response.getEntity();
		String result = null;
		if (entity != null){
			result = EntityUtils.toString(entity, "utf-8");
		}
		EntityUtils.consume(entity);
		response.close();
		return result;
    }
    
    public static void main(String []args){
    	try{
	    	String getData = doGet("http://www.oschina.net/",null);
	    	System.out.println(getData);
	    	System.out.println("----------------------鍒嗗壊绾�-----------------------");
	    	String postData = doPost("http://www.oschina.net/",null);
	    	System.out.println(postData);
    	}catch(Exception ex){
    		ex.printStackTrace();
    	}
    }
    
}
